// components/project/ProjectFormDialog.tsx
"use client"

import React, { useEffect, useState } from 'react'
import { Plus, X, Upload, FileText, MapPin, Target, Download, Loader2, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { useProjects, useProjectForm } from '@/hooks/project'
import type { Project, ProjectStatus } from '@/types/project'

// 项目状态选项
const PROJECT_STATUS_OPTIONS: { value: ProjectStatus; label: string }[] = [
  { value: "进行中", label: "进行中" },
  { value: "已完成", label: "已完成" }
]

interface ProjectFormDialogProps {
  project?: Project
  isOpen: boolean
  onClose: () => void
  onSuccess: () => void
}

export function ProjectFormDialog({ project, isOpen, onClose, onSuccess }: ProjectFormDialogProps) {
  const { createProject, updateProject, loading, canCreateProject, canEditProject, downloadAttachment, deleteAttachment } = useProjects()
  const { formData, errors, updateField, validateForm, resetForm, setFormData } = useProjectForm(project)
  
  // 附件相关状态
  const [downloadingFiles, setDownloadingFiles] = useState<Set<string>>(new Set())
  const [deletingFiles, setDeletingFiles] = useState<Set<string>>(new Set())
  const [attachmentMessage, setAttachmentMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null)

  // 权限检查
  useEffect(() => {
    if (isOpen) {
      if (project && !canEditProject) {
        onClose()
        return
      }
      if (!project && !canCreateProject) {
        onClose()
        return
      }
    }
  }, [isOpen, project, canCreateProject, canEditProject, onClose])

  useEffect(() => {
    if (isOpen && project) {
      setFormData({
        name: project.name || '',
        description: project.description || '',
        crop_type: project.crop_type || '',
        location: project.location || '',
        start_date: project.start_date || '',
        end_date: project.end_date || '',
        manager: project.manager || '',
        status: project.status,
        budget: project.budget ? project.budget.toString() : '',
        objectives: project.objectives ? project.objectives.join('\n') : '',
        attachments: []
      })
    } else if (isOpen && !project) {
      resetForm()
    }
  }, [isOpen, project, setFormData, resetForm])

  // 处理附件下载
  const handleDownloadAttachment = async (attachmentId: string, fileName: string) => {
    if (!project) return
    
    setDownloadingFiles(prev => new Set(prev).add(attachmentId))
    setAttachmentMessage(null)
    
    try {
      await downloadAttachment(project.id, attachmentId, fileName)
      setAttachmentMessage({ type: 'success', text: `文件 "${fileName}" 下载成功` })
      
      // 3秒后自动清除成功消息
      setTimeout(() => {
        setAttachmentMessage(null)
      }, 3000)
    } catch (error: any) {
      console.error('下载失败:', error)
      setAttachmentMessage({ 
        type: 'error', 
        text: `下载失败: ${error.message || '未知错误'}` 
      })
    } finally {
      setDownloadingFiles(prev => {
        const newSet = new Set(prev)
        newSet.delete(attachmentId)
        return newSet
      })
    }
  }

  // 处理附件删除
  const handleDeleteAttachment = async (attachmentId: string, fileName: string) => {
    if (!project) return
    
    if (!confirm(`确定要删除附件 "${fileName}" 吗？此操作无法撤销。`)) {
      return
    }
    
    setDeletingFiles(prev => new Set(prev).add(attachmentId))
    setAttachmentMessage(null)
    
    try {
      const result = await deleteAttachment(project.id, attachmentId)
      if (result.success) {
        setAttachmentMessage({ type: 'success', text: `文件 "${fileName}" 删除成功` })
        // 触发重新获取项目数据以更新附件列表
        onSuccess()
        
        setTimeout(() => {
          setAttachmentMessage(null)
        }, 3000)
      } else {
        setAttachmentMessage({ 
          type: 'error', 
          text: result.message || '删除失败' 
        })
      }
    } catch (error: any) {
      console.error('删除失败:', error)
      setAttachmentMessage({ 
        type: 'error', 
        text: `删除失败: ${error.message || '未知错误'}` 
      })
    } finally {
      setDeletingFiles(prev => {
        const newSet = new Set(prev)
        newSet.delete(attachmentId)
        return newSet
      })
    }
  }

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 格式化上传时间
  const formatUploadTime = (dateString: string): string => {
    try {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    } catch {
      return dateString
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    // 权限检查
    if (project && !canEditProject) {
      console.error('没有编辑权限')
      return
    }
    if (!project && !canCreateProject) {
      console.error('没有创建权限')
      return
    }
    
    if (!validateForm()) {
      return
    }

    try {
      let result
      if (project) {
        result = await updateProject(project.id, formData)
      } else {
        result = await createProject(formData)
      }

      if (result.success) {
        onSuccess()
        onClose()
        resetForm()
      }
    } catch (error) {
      console.error('操作失败:', error)
    }
  }

  if (!isOpen) return null

  // 权限检查 - 如果没有相应权限，显示错误信息
  const hasPermission = project ? canEditProject : canCreateProject
  if (!hasPermission) {
    return (
      <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[9999]">
        <div className="bg-white rounded-lg p-6 w-full max-w-md relative z-[10000]">
          <div className="text-center">
            <h2 className="text-xl font-bold mb-4 text-red-600">权限不足</h2>
            <p className="text-gray-600 mb-4">
              {project ? '您没有编辑项目的权限' : '您没有创建项目的权限'}
            </p>
            <Button onClick={onClose}>关闭</Button>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[9999]">
      <div className="bg-white rounded-lg p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto relative z-[10000]">
        <div className="mb-6">
          <h2 className="text-2xl font-bold">
            {project ? '编辑项目' : '创建新项目'}
          </h2>
        </div>
        


        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 基本信息区域 */}
          <div className="border rounded-lg p-4 space-y-4 bg-blue-50/30">
            <h3 className="font-semibold text-lg mb-4 flex items-center text-blue-700">
              <FileText className="w-5 h-5 mr-2" />
              基本信息
            </h3>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="name">项目名称 *</Label>
                <Input
                  id="name"
                  value={formData.name || ''}
                  onChange={(e) => updateField('name', e.target.value)}
                  placeholder="请输入项目名称"
                  className={errors.name ? 'border-red-500' : ''}
                />
                {errors.name && <p className="text-red-500 text-sm mt-1">{errors.name}</p>}
              </div>
              <div>
                <Label htmlFor="manager">项目负责人</Label>
                <Input
                  id="manager"
                  value={formData.manager || ''}
                  onChange={(e) => updateField('manager', e.target.value)}
                  placeholder="请输入项目负责人姓名"
                />
              </div>
              <div>
                <Label htmlFor="crop_type">作物类型</Label>
                <Input
                  id="crop_type"
                  value={formData.crop_type || ''}
                  onChange={(e) => updateField('crop_type', e.target.value)}
                  placeholder="请输入作物类型"
                  className={errors.crop_type ? 'border-red-500' : ''}
                />
                {errors.crop_type && <p className="text-red-500 text-sm mt-1">{errors.crop_type}</p>}
              </div>

              {/* 项目状态 - 仅在编辑模式下显示 */}
              {project && (
                <div>
                  <Label htmlFor="status">项目状态</Label>
                  <Select 
                    value={formData.status || '进行中'} 
                    onValueChange={(value) => updateField('status', value as ProjectStatus)}
                  >
                    <SelectTrigger className="w-full">
                      <SelectValue placeholder="选择项目状态" />
                    </SelectTrigger>
                    <SelectContent 
                      className="z-[10002] relative"
                      side="bottom" 
                      align="start" 
                      position="popper"
                      avoidCollisions={true}
                      collisionPadding={8}
                    >
                      {PROJECT_STATUS_OPTIONS.map((status) => (
                        <SelectItem key={status.value} value={status.value}>
                          {status.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              )}
            </div>

            <div>
              <Label htmlFor="description">项目描述</Label>
              <Textarea
                id="description"
                value={formData.description || ''}
                onChange={(e) => updateField('description', e.target.value)}
                placeholder="请输入项目描述"
                rows={3}
                className={errors.description ? 'border-red-500' : ''}
              />
              {errors.description && <p className="text-red-500 text-sm mt-1">{errors.description}</p>}
            </div>
          </div>

          {/* 时间和地点区域 */}
          <div className="border rounded-lg p-4 space-y-4 bg-green-50/30">
            <h3 className="font-semibold text-lg mb-4 flex items-center text-green-700">
              <MapPin className="w-5 h-5 mr-2" />
              时间和地点
            </h3>
            
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <Label htmlFor="start_date">开始日期 *</Label>
                <Input
                  id="start_date"
                  type="month"
                  value={formData.start_date || ''}
                  onChange={(e) => updateField('start_date', e.target.value)}
                  className={errors.start_date ? 'border-red-500' : ''}
                />
                {errors.start_date && <p className="text-red-500 text-sm mt-1">{errors.start_date}</p>}
              </div>

              <div>
                <Label htmlFor="end_date">结束日期 *</Label>
                <Input
                  id="end_date"
                  type="month"
                  value={formData.end_date || ''}
                  onChange={(e) => updateField('end_date', e.target.value)}
                  className={errors.end_date ? 'border-red-500' : ''}
                />
                {errors.end_date && <p className="text-red-500 text-sm mt-1">{errors.end_date}</p>}
              </div>

              <div>
                <Label htmlFor="location">项目地点</Label>
                <Input
                  id="location"
                  value={formData.location || ''}
                  onChange={(e) => updateField('location', e.target.value)}
                  placeholder="请输入项目地点"
                  className={errors.location ? 'border-red-500' : ''}
                />
                {errors.location && <p className="text-red-500 text-sm mt-1">{errors.location}</p>}
              </div>
            </div>
          </div>

          {/* 预算和目标区域 */}
          <div className="border rounded-lg p-4 space-y-4 bg-yellow-50/30">
            <h3 className="font-semibold text-lg mb-4 flex items-center text-yellow-700">
              <Target className="w-5 h-5 mr-2" />
              预算和目标
            </h3>
            
            <div>
              <Label htmlFor="budget">项目预算（元）</Label>
              <Input
                id="budget"
                type="number"
                value={formData.budget || ''}
                onChange={(e) => updateField('budget', e.target.value)}
                placeholder="请输入项目预算"
                min="0"
                step="0.01"
                className={errors.budget ? 'border-red-500' : ''}
              />
              {errors.budget && <p className="text-red-500 text-sm mt-1">{errors.budget}</p>}
            </div>

            <div>
              <Label htmlFor="objectives">项目目标</Label>
              <Textarea
                id="objectives"
                value={formData.objectives || ''}
                onChange={(e) => updateField('objectives', e.target.value)}
                placeholder="请输入项目目标，每行一个目标"
                rows={4}
              />
            </div>
          </div>

          {/* 附件管理区域 */}
          <div className="border rounded-lg p-4 space-y-4 bg-purple-50/30">
            <h3 className="font-semibold text-lg mb-4 flex items-center">
              <Upload className="w-5 h-5 mr-2" />
              附件管理
            </h3>
            
            {/* 附件操作消息 */}
            {attachmentMessage && (
              <div className={`p-3 rounded-lg ${
                attachmentMessage.type === 'success' 
                  ? 'bg-green-50 border border-green-200 text-green-700' 
                  : 'bg-red-50 border border-red-200 text-red-700'
              }`}>
                <p className="text-sm">{attachmentMessage.text}</p>
              </div>
            )}
            
            {/* 已上传的附件 - 仅在编辑模式下显示 */}
            {project && project.attachments && project.attachments.length > 0 && (
              <div>
                <Label className="text-sm font-medium text-gray-700">
                  已上传的文件 ({project.attachments.length})
                </Label>
                <div className="mt-2 space-y-2 max-h-40 overflow-y-auto border rounded p-2 bg-white">
                  {project.attachments.map((attachment) => (
                    <div key={attachment.id} className="flex items-center justify-between p-3 border rounded hover:bg-gray-50">
                      <div className="flex items-center flex-1 min-w-0">
                        <FileText className="w-4 h-4 mr-2 text-green-500 flex-shrink-0" />
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium truncate" title={attachment.name}>
                            {attachment.name}
                          </p>
                          <p className="text-xs text-gray-500">
                            {formatFileSize(attachment.size)} · {formatUploadTime(attachment.uploaded_at)}
                            {attachment.uploaded_by_name && ` · 上传者：${attachment.uploaded_by_name}`}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center space-x-1 flex-shrink-0">
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          disabled={downloadingFiles.has(attachment.id)}
                          onClick={() => handleDownloadAttachment(attachment.id, attachment.name)}
                          className="h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600"
                          title="下载文件"
                        >
                          {downloadingFiles.has(attachment.id) ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : (
                            <Download className="w-4 h-4" />
                          )}
                        </Button>
                        {canEditProject && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            disabled={deletingFiles.has(attachment.id)}
                            onClick={() => handleDeleteAttachment(attachment.id, attachment.name)}
                            className="h-8 w-8 p-0 hover:bg-red-50 hover:text-red-600"
                            title="删除文件"
                          >
                            {deletingFiles.has(attachment.id) ? (
                              <Loader2 className="w-4 h-4 animate-spin" />
                            ) : (
                              <Trash2 className="w-4 h-4" />
                            )}
                          </Button>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
            
            <div>
              <Label htmlFor="fileUpload">上传新附件</Label>
              <div className="mt-2">
                <input
                  id="fileUpload"
                  type="file"
                  multiple
                  accept=".zip,.xlsx,.xls,.csv,.jpg,.jpeg,.png,.gif,.webp,.txt,.dat,.json,.pdf,.doc,.docx"
                  onChange={(e) => {
                    if (e.target.files) {
                      const files = Array.from(e.target.files)
                      updateField('attachments', [...formData.attachments, ...files])
                    }
                  }}
                  className="hidden"
                />
                <div
                  onClick={() => document.getElementById('fileUpload')?.click()}
                  className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer hover:border-blue-400 hover:bg-blue-50/30 transition-colors"
                >
                  <Upload className="w-8 h-8 mx-auto mb-2 text-gray-400" />
                  <p className="text-sm text-gray-600 mb-1">点击选择文件或拖拽文件至此</p>
                  <p className="text-xs text-gray-500">支持上传光谱数据、图像、传感器数据、Excel表格等</p>
                </div>
              </div>
            </div>

            {/* 新选择的文件列表 */}
            {formData.attachments.length > 0 && (
              <div>
                <Label className="flex items-center">
                  <FileText className="w-4 h-4 mr-1" />
                  待上传的文件 ({formData.attachments.length})
                </Label>
                <div className="mt-3 space-y-2 max-h-40 overflow-y-auto border rounded p-2 bg-yellow-50">
                  {formData.attachments.map((file, index) => (
                    <div key={index} className="flex items-center justify-between p-3 bg-white rounded border hover:shadow-sm transition-shadow">
                      <div className="flex items-center flex-1 min-w-0">
                        <FileText className="w-4 h-4 mr-2 text-blue-500 flex-shrink-0" />
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium truncate" title={file.name}>{file.name}</p>
                          <p className="text-xs text-gray-500">
                            {(file.size / 1024 / 1024).toFixed(2)} MB
                          </p>
                        </div>
                      </div>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          const newAttachments = formData.attachments.filter((_, i) => i !== index)
                          updateField('attachments', newAttachments)
                        }}
                        className="text-red-500 hover:text-red-700 hover:bg-red-50 h-8 w-8 p-0 flex-shrink-0"
                        title="删除文件"
                      >
                        <X className="w-4 h-4" />
                      </Button>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* 提交按钮 */}
          <div className="flex justify-end space-x-2 pt-4">
            <Button type="button" variant="outline" onClick={onClose}>
              取消
            </Button>
            <Button type="submit" disabled={loading}>
              {loading ? '保存中...' : (project ? '更新项目' : '创建项目')}
            </Button>
          </div>
        </form>
      </div>
    </div>
  )
}